package com.triones.api.service.interlace.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.getui.push.v2.sdk.dto.res.CidStatusDTO;
import com.ruoyi.common.enums.PushNotificationEnum;
import com.ruoyi.common.utils.PushResult;
import com.triones.api.entity.DeviceDO;
import com.triones.api.entity.LanguageDO;
import com.triones.api.entity.bo.NoticeBO;
import com.triones.api.entity.interlace.bo.request.ListAllBalancesRequest;
import com.triones.api.entity.interlace.dto.InterlaceInternalTransferDO;
import com.triones.api.entity.interlace.dto.InterlaceNoticeDO;
import com.triones.api.entity.interlace.dto.InterlaceNoticeMemberDO;
import com.triones.api.mapper.DeviceMapper;
import com.triones.api.mapper.LanguageMapper;
import com.triones.api.mapper.interlace.InterlaceNoticeMapper;
import com.triones.api.mapper.interlace.InterlaceNoticeMemberMapper;
import com.triones.api.mapper.interlace.InterlaceNoticeSceneMapper;
import com.triones.api.service.interlace.PushService;
import com.triones.api.service.third.GeTuiPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 推送管理
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PushServiceImpl implements PushService {

    private final GeTuiPushService geTuiPushService;

    private final InterlaceNoticeMapper interlaceNoticeMapper;

    private final InterlaceNoticeMemberMapper interlaceNoticeMemberMapper;

    private final InterlaceNoticeSceneMapper interlaceNoticeSceneMapper;

    private final DeviceMapper deviceMapper;

    private final LanguageMapper languageMapper;

    @Async
    @Override
    public void push(String type, String zhContent, String enContent, String jaContent, Long uid) {
        PushNotificationEnum notification = PushNotificationEnum.fromPushType(type);
        String language = "en";
        LanguageDO languageDO = languageMapper.selectOne(new LambdaQueryWrapper<LanguageDO>()
            .eq(LanguageDO::getUid, uid)
            .last("limit 1"));
        if (languageDO != null) {
            language = languageDO.getLanguage();
        }
        String title = language.equals("zh") ? notification.getZhTitle() : language.equals("en") ? notification.getEnTitle() : notification.getJaTitle();
        String body = language.equals("zh") ? zhContent : language.equals("en") ? enContent : jaContent;
        DeviceDO deviceDO = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceDO>()
            .eq(DeviceDO::getUid, uid)
            .last("limit 1"));
        InterlaceNoticeDO notice = new InterlaceNoticeDO();
        notice.setZhTitle(notification.getZhTitle());
        notice.setEnTitle(notification.getEnTitle());
        notice.setJaTitle(notification.getJaTitle());
        notice.setZhContent(zhContent);
        notice.setEnContent(enContent);
        notice.setJaContent(jaContent);
        notice.setNtfObjRange("customer");
        notice.setSceneType(type);
        notice.setCreateTime(System.currentTimeMillis());
        notice.setSysDel("0");
        interlaceNoticeMapper.insert(notice);
        if (deviceDO != null) {
            InterlaceNoticeMemberDO noticeMember = new InterlaceNoticeMemberDO();
            noticeMember.setNid(notice.getId());
            noticeMember.setUid(uid);
            noticeMember.setCreateTime(System.currentTimeMillis());
            noticeMember.setIsRead("0");
            noticeMember.setDel("0");
            noticeMember.setIsPush("0");
            noticeMember.setPushTime(System.currentTimeMillis());
            noticeMember.setCid(deviceDO.getDeviceId());
            noticeMember.setPushChannel("0");
            interlaceNoticeMemberMapper.insert(noticeMember);
            try {
                PushResult queryUserStatusResult = geTuiPushService.queryUserStatus(deviceDO.getDeviceId());
                if (queryUserStatusResult.isSuccess()) {
                    if ("online".equals(queryUserStatusResult.getErrorMsg())) {
                        /** 在线单推 */
                        PushResult result = geTuiPushService.pushToSingle(deviceDO.getDeviceId(), title, body);
                        log.info("在线单推结果 -> {},信息{}", result.isSuccess(), result.getErrorMsg());
                        noticeMember.setPushChannel("1");
                        if (result.isSuccess()) {
                            noticeMember.setIsPush("1");
                        } else {
                            noticeMember.setIsPush("2");
                            noticeMember.setFailReason(queryUserStatusResult.getErrorMsg());
                        }
                    } else {
                        /** 离线推送 */
                        PushResult pushResult = geTuiPushService.offlinePush(deviceDO.getDeviceId(), title, body);
                        log.info("离线推送结果 -> {},信息{}", pushResult.isSuccess(), pushResult.getErrorMsg());
                        noticeMember.setPushChannel("2");
                        if (pushResult.isSuccess()) {
                            noticeMember.setIsPush("1");
                        } else {
                            noticeMember.setIsPush("2");
                            noticeMember.setFailReason(queryUserStatusResult.getErrorMsg());
                        }
                    }
                } else {
                    noticeMember.setIsPush("0");
                    noticeMember.setFailReason("未查询到用户设备的具体状态");
                }
            } catch (Exception e) {
                log.error("推送失败 -> {}", e.getMessage());
                noticeMember.setIsPush("2");
                noticeMember.setFailReason(e.getMessage());
            }
            interlaceNoticeMemberMapper.updateById(noticeMember);
        } else {
            InterlaceNoticeMemberDO noticeMember = new InterlaceNoticeMemberDO();
            noticeMember.setNid(notice.getId());
            noticeMember.setUid(uid);
            noticeMember.setCreateTime(System.currentTimeMillis());
            noticeMember.setIsRead("0");
            noticeMember.setDel("0");
            noticeMember.setIsPush("0");
            noticeMember.setCid("");
            noticeMember.setFailReason("未查询到用户设备信息");
            noticeMember.setPushChannel("0");
            interlaceNoticeMemberMapper.insert(noticeMember);
        }
    }
    @Async
    @Override
    public void push(NoticeBO bo, List<Long> uidList) {
        InterlaceNoticeDO notice = new InterlaceNoticeDO();
        notice.setZhTitle(bo.getZhTitle());
        notice.setEnTitle(bo.getEnTitle());
        notice.setJaTitle(bo.getJaTitle());
        notice.setZhContent(bo.getZhContent());
        notice.setEnContent(bo.getEnContent());
        notice.setJaContent(bo.getJaContent());
        notice.setNtfObjRange(bo.getNtfObjRange());
        notice.setSceneType(bo.getSceneType());
        notice.setCreateTime(System.currentTimeMillis());
        notice.setSysDel("0");
        interlaceNoticeMapper.insert(notice);
        for (Long aLong : uidList) {
            String language = "en";
            LanguageDO languageDO = languageMapper.selectOne(new LambdaQueryWrapper<LanguageDO>()
                .eq(LanguageDO::getUid, aLong)
                .last("limit 1"));
            if (languageDO != null) {
                language = languageDO.getLanguage();
            }
            String title = language.equals("zh") ? bo.getZhTitle() : language.equals("en") ? bo.getEnTitle() : bo.getJaTitle();
            String body = language.equals("zh") ? bo.getZhContent() : language.equals("en") ? bo.getEnContent() : bo.getJaContent();
            DeviceDO deviceDO = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceDO>()
                .eq(DeviceDO::getUid, aLong)
                .last("limit 1"));
            if (deviceDO != null) {
                InterlaceNoticeMemberDO noticeMember = new InterlaceNoticeMemberDO();
                noticeMember.setNid(notice.getId());
                noticeMember.setUid(aLong);
                noticeMember.setCreateTime(System.currentTimeMillis());
                noticeMember.setIsRead("0");
                noticeMember.setDel("0");
                noticeMember.setIsPush("0");
                noticeMember.setPushTime(System.currentTimeMillis());
                noticeMember.setCid(deviceDO.getDeviceId());
                noticeMember.setPushChannel("0");
                interlaceNoticeMemberMapper.insert(noticeMember);
                try {
                    PushResult queryUserStatusResult = geTuiPushService.queryUserStatus(deviceDO.getDeviceId());
                    if (queryUserStatusResult.isSuccess()) {
                        if ("online".equals(queryUserStatusResult.getErrorMsg())) {
                            /** 在线单推 */
                            PushResult result = geTuiPushService.pushToSingle(deviceDO.getDeviceId(), title, body);
                            log.info("在线单推结果 -> {},信息{}", result.isSuccess(), result.getErrorMsg());
                            noticeMember.setPushChannel("1");
                            if (result.isSuccess()) {
                                noticeMember.setIsPush("1");
                            } else {
                                noticeMember.setIsPush("2");
                                noticeMember.setFailReason(queryUserStatusResult.getErrorMsg());
                            }
                        } else {
                            /** 离线推送 */
                            PushResult pushResult = geTuiPushService.offlinePush(deviceDO.getDeviceId(), title, body);
                            log.info("离线推送结果 -> {},信息{}", pushResult.isSuccess(), pushResult.getErrorMsg());
                            noticeMember.setPushChannel("2");
                            if (pushResult.isSuccess()) {
                                noticeMember.setIsPush("1");
                            } else {
                                noticeMember.setIsPush("2");
                                noticeMember.setFailReason(queryUserStatusResult.getErrorMsg());
                            }
                        }
                    } else {
                        noticeMember.setIsPush("0");
                        noticeMember.setFailReason("未查询到用户设备的具体状态");
                    }
                } catch (Exception e) {
                    log.error("推送失败 -> {}", e.getMessage());
                    noticeMember.setIsPush("2");
                    noticeMember.setFailReason(e.getMessage());
                }
                interlaceNoticeMemberMapper.updateById(noticeMember);
            } else {
                InterlaceNoticeMemberDO noticeMember = new InterlaceNoticeMemberDO();
                noticeMember.setNid(notice.getId());
                noticeMember.setUid(aLong);
                noticeMember.setCreateTime(System.currentTimeMillis());
                noticeMember.setIsRead("0");
                noticeMember.setDel("0");
                noticeMember.setIsPush("0");
                noticeMember.setCid("");
                noticeMember.setFailReason("未查询到用户设备信息");
                noticeMember.setPushChannel("0");
                interlaceNoticeMemberMapper.insert(noticeMember);
            }
        }
    }
}
